// Package comsdk 提供服务组件脚手架的核心SDK，集成了服务器、通信、注册和安全验证等功能
package comsdk

import (
	"fmt"
	"net/http"
)

// ErrorCode 错误码类型
type ErrorCode int

// 预定义错误码
const (
	// 系统级错误码 (1-999)
	ErrCodeSystem        ErrorCode = 100 // 系统错误
	ErrCodeConfiguration ErrorCode = 101 // 配置错误
	ErrCodeNetwork       ErrorCode = 102 // 网络错误
	ErrCodeTimeout       ErrorCode = 103 // 超时错误
	ErrCodeSecurity      ErrorCode = 104 // 安全验证错误
	ErrCodeEncryption    ErrorCode = 105 // 加解密错误

	// 业务级错误码 (1000-1999)
	ErrCodeBadRequest   ErrorCode = 1000 // 无效请求
	ErrCodeUnauthorized ErrorCode = 1001 // 未授权
	ErrCodeForbidden    ErrorCode = 1002 // 禁止访问
	ErrCodeNotFound     ErrorCode = 1003 // 资源不存在
	ErrCodeValidation   ErrorCode = 1004 // 数据验证错误
	ErrCodeDuplicate    ErrorCode = 1005 // 资源重复
)

// errorCodeToHTTPStatus 错误码到HTTP状态码的映射
var errorCodeToHTTPStatus = map[ErrorCode]int{
	ErrCodeSystem:        http.StatusInternalServerError,
	ErrCodeConfiguration: http.StatusInternalServerError,
	ErrCodeNetwork:       http.StatusBadGateway,
	ErrCodeTimeout:       http.StatusGatewayTimeout,
	ErrCodeSecurity:      http.StatusUnauthorized,
	ErrCodeEncryption:    http.StatusBadRequest,

	ErrCodeBadRequest:   http.StatusBadRequest,
	ErrCodeUnauthorized: http.StatusUnauthorized,
	ErrCodeForbidden:    http.StatusForbidden,
	ErrCodeNotFound:     http.StatusNotFound,
	ErrCodeValidation:   http.StatusBadRequest,
	ErrCodeDuplicate:    http.StatusConflict,
}

// AppError 应用错误类型
type AppError struct {
	Code    ErrorCode `json:"code"`             // 错误码
	Message string    `json:"message"`          // 错误消息
	Detail  string    `json:"detail,omitempty"` // 错误详情
	Err     error     `json:"-"`                // 原始错误
}

// NewAppError 创建新的应用错误
func NewAppError(code ErrorCode, message string, detail string, err error) *AppError {
	return &AppError{
		Code:    code,
		Message: message,
		Detail:  detail,
		Err:     err,
	}
}

// Error 实现error接口
func (e *AppError) Error() string {
	if e.Detail != "" {
		return fmt.Sprintf("[%d] %s: %s", e.Code, e.Message, e.Detail)
	}
	return fmt.Sprintf("[%d] %s", e.Code, e.Message)
}

// Unwrap 返回包装的错误，实现错误链
func (e *AppError) Unwrap() error {
	return e.Err
}

// HTTPStatusCode 返回对应的HTTP状态码
func (e *AppError) HTTPStatusCode() int {
	if status, exists := errorCodeToHTTPStatus[e.Code]; exists {
		return status
	}
	return http.StatusInternalServerError
}

// StandardResponse 标准响应结构
type StandardResponse struct {
	Success bool        `json:"success"`            // 是否成功
	Message string      `json:"message,omitempty"`  // 消息
	Data    interface{} `json:"data,omitempty"`     // 数据
	Error   *AppError   `json:"error,omitempty"`    // 错误信息
	TraceID string      `json:"trace_id,omitempty"` // 请求跟踪ID
}

// NewSuccessResponse 创建成功响应
func NewSuccessResponse(message string, data interface{}) *StandardResponse {
	return &StandardResponse{
		Success: true,
		Message: message,
		Data:    data,
	}
}

// NewErrorResponse 创建错误响应
func NewErrorResponse(err *AppError) *StandardResponse {
	return &StandardResponse{
		Success: false,
		Error:   err,
	}
}

// SendErrorResponse 发送错误响应
func SendErrorResponse(w http.ResponseWriter, err *AppError, traceID string) {
	resp := NewErrorResponse(err)
	resp.TraceID = traceID
	status := err.HTTPStatusCode()
	JSONResponse(w, status, resp)
}

// SendSuccessResponse 发送成功响应
func SendSuccessResponse(w http.ResponseWriter, message string, data interface{}, traceID string) {
	resp := NewSuccessResponse(message, data)
	resp.TraceID = traceID
	JSONResponse(w, http.StatusOK, resp)
}

// IsAppError 判断错误是否为AppError类型
func IsAppError(err error) (*AppError, bool) {
	if err == nil {
		return nil, false
	}

	appErr, ok := err.(*AppError)
	return appErr, ok
}

// WrapError 包装错误为AppError
func WrapError(err error, code ErrorCode, message string) *AppError {
	if err == nil {
		return nil
	}

	// 如果已经是AppError，且没有指定新的消息，则保留原消息
	if appErr, ok := err.(*AppError); ok {
		if message == "" {
			message = appErr.Message
		}
		return NewAppError(code, message, appErr.Detail, appErr.Err)
	}

	return NewAppError(code, message, err.Error(), err)
}
